package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.cdb;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdb.code.CDBCostConfig;
import com.gzhryc.shared_device.cdb.code.dao.db.CDBFeeTemplate;
import com.gzhryc.shared_device.cdb.code.services.CDBFeeTemplateService;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdb.CDBFeeTemplateDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdb.CDBFeeTemplateListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdb.CDBFeeTemplateSaveRequest;

public class CDBFeeTemplateController {

    @Route(value = "/agent/api/v1/cdb/fee_template/list.data")
    public CDBFeeTemplateListResponse list(HttpServletRequest request) {
        CDBFeeTemplateListResponse apiResp = new CDBFeeTemplateListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
        if (loginUser != null) {
            List<CDBFeeTemplate> cdbFeeTemplateList = null;
            if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                cdbFeeTemplateList = CDBFeeTemplateService.self().findByUserId(loginUser.getId());
            }else if(ERoleType.Partner.index().equals(loginUser.getRoleType())){
                cdbFeeTemplateList = CDBFeeTemplateService.self().findByUserId(loginUser.getParentId());
            }

            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setItems(new ArrayList<>());

            //获取全局
            CDBCostConfig config = ConfigUtils.getCDBCostConfig();
            CDBFeeTemplateListResponse.Item item = new CDBFeeTemplateListResponse.Item();
            item.setTitle("全局模版");
            item.setDepositPrice(config.getDepositMoneyStr());
            item.setDayMaxPrice(config.getDayMaxMoneyStr());
            item.setPayIntervalPrice(config.getPayIntervalMoneyStr());
            item.setFreeTimes(config.getFreeTimes());

            apiResp.getBody().getItems().add(item);

            if(cdbFeeTemplateList != null && cdbFeeTemplateList.size() > 0){
                for(CDBFeeTemplate feeTemplate : cdbFeeTemplateList){
                    item = new CDBFeeTemplateListResponse.Item();
                    item.setId(feeTemplate.getId());
                    item.setTitle(feeTemplate.getTitle());
                    item.setDepositPrice(feeTemplate.getDepositMoneyStr());
                    item.setDayMaxPrice(feeTemplate.getDayMaxMoneyStr());
                    item.setPayIntervalPrice(feeTemplate.getPayIntervalMoneyStr());
                    item.setFreeTimes(feeTemplate.getFreeTimes());

                    apiResp.getBody().getItems().add(item);
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdb/fee_template/save.do")
    public DefaultAPIResponse save(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存收费模版失败");
        CDBFeeTemplateSaveRequest apiReq = WebUtils.getJsonRequest(request, CDBFeeTemplateSaveRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Long userId = loginUser.getId();
                if(!ERoleType.Agent.index().equals(loginUser.getRoleType())){
                    if(ERoleType.Partner.index().equals(loginUser.getRoleType())) {
                        userId = loginUser.getParentId();
                    }else{
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限保存收费模版");
                        return apiResp;
                    }
                }

                Integer depositMoney = null;
                Integer dayMaxMoney = null;
                Integer payIntervalMoney = null;
                if(StringTools.isBlank(apiReq.getBody().getTitle())){
                    apiResp.setMsg("请填写模版标题");
                    return apiResp;
                }
                if(apiReq.getBody().getDepositPrice() != null){
                    depositMoney = NumberTools.changeMoney(apiReq.getBody().getDepositPrice());
                    if(depositMoney < 1 || depositMoney > 9900){
                        apiResp.setMsg("押金设置范围1-99元");
                        return apiResp;
                    }
                }else {
                    apiResp.setMsg("请填写押金");
                    return apiResp;
                }
                if(apiReq.getBody().getDayMaxPrice() != null){
                    dayMaxMoney = NumberTools.changeMoney(apiReq.getBody().getDayMaxPrice());
                    if(dayMaxMoney < 1 || dayMaxMoney > 3000){
                        apiResp.setMsg("日封顶设置范围1-30元");
                        return apiResp;
                    }
                }else {
                    apiResp.setMsg("请填写日封顶金额");
                    return apiResp;
                }
                if(apiReq.getBody().getPayIntervalPrice() != null){
                    payIntervalMoney = NumberTools.changeMoney(apiReq.getBody().getPayIntervalPrice());
                    if(payIntervalMoney < 1 || payIntervalMoney > 1000){
                        apiResp.setMsg("每小时收费范围1-10元");
                        return apiResp;
                    }
                }else {
                    apiResp.setMsg("请填写每小时收费");
                    return apiResp;
                }

                if(apiReq.getBody().getFreeTimes() != null){
                    if(apiReq.getBody().getFreeTimes() < 1 || apiReq.getBody().getFreeTimes() > 10){
                        apiResp.setMsg("免费时长范围1-10分钟");
                        return apiResp;
                    }
                }else{
                    apiResp.setMsg("请填写免费时长");
                    return apiResp;
                }

                CDBFeeTemplate cdbFeeTemplate = new CDBFeeTemplate();
                cdbFeeTemplate.setId(apiReq.getBody().getId());
                cdbFeeTemplate.setUserId(userId);
                cdbFeeTemplate.setTitle(apiReq.getBody().getTitle());
                cdbFeeTemplate.setDepositMoney(depositMoney);
                cdbFeeTemplate.setDayMaxMoney(dayMaxMoney);
                cdbFeeTemplate.setPayIntervalMoney(payIntervalMoney);
                cdbFeeTemplate.setFreeTimes(apiReq.getBody().getFreeTimes());

                if(cdbFeeTemplate.getId() != null) {
                    try {
                        if(CDBFeeTemplateService.self().updateNotNull(cdbFeeTemplate)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else{
                    try {
                        if(CDBFeeTemplateService.self().add(cdbFeeTemplate)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdb/fee_template/del.do")
    public DefaultAPIResponse doDel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除收费模版失败");
        CDBFeeTemplateDelRequest apiReq = WebUtils.getJsonRequest(request, CDBFeeTemplateDelRequest.class);
        if (apiReq != null && apiReq.getBody().getId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser == null || !ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限删除");
                return apiResp;
            }
            Long total = PlaceBusinessConfigService.self().countByFeeTemplateId(EBusinessType.CDB.index(),apiReq.getBody().getId());
            if(total != null && total > 0){
                apiResp.setMsg("该收费模版正在使用，不允许删除");
                return apiResp;
            }

            try {
                if(CDBFeeTemplateService.self().deleteById(apiReq.getBody().getId())){
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }

}
